package com.cbank.controller.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cbank.constants.Result;
import com.cbank.constants.ResultCode;
import com.cbank.domain.User;
import com.cbank.service.UserService;
import com.cbank.utils.UniqueKeyGenerator;

@Controller
@RequestMapping("/web/user")
public class WebUserController {
	public static final String COOKIE_UID = "uid";
	public static final String COOKIE_TOKEN = "token";
	Logger l= Logger.getLogger(WebUserController.class);
	@Autowired
	private UserService userService;

	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String loginPager(HttpServletResponse response, Model model) {
		return "/login";
	}

	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public Result<User> login(@RequestParam(value = "name") String name, @RequestParam(value = "pwd") String pwd,
			HttpServletResponse response, Model model) {
		User user = userService.getByNamePwd(name, pwd);
		l.info("进入login");
		if (user == null) {
			return new Result<User>(ResultCode.ERROR_PASSWORD.getCode(), ResultCode.ERROR_PASSWORD.getMsg(), null);
		}
		user.setToken(UniqueKeyGenerator.generateToken());
		Cookie cookieUid = generateCookie(COOKIE_UID, user.getViewId()+"");
		Cookie cookieToken = generateCookie(COOKIE_TOKEN, user.getToken());
		response.addCookie(cookieUid);
		response.addCookie(cookieToken);
		userService.save(user);
		return new Result<User>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(), user);
	}

	private Cookie generateCookie(String key, String value) {
		Cookie cookie = new Cookie(key, value);
		// 设置Maximum Age
		cookie.setMaxAge(Integer.MAX_VALUE);// 生命周期
		// 设置cookie路径为当前项目路径
		cookie.setPath("/");
		// cookieUid.setDomain(".cakeboss.com.cn");
		return cookie;
	}
}
